<template>
  <div class="urlBox">
    <!-- v-show="((mindex > 0 && active[mindex - 1] > -1) || mindex === 0) && mindex < maxLevel" 需要隐藏时使用，空间占的更少-->
    <div
      class="urlList"
      v-for="(group, mindex) in group1"
      :key="mindex"
      v-show="mindex < maxLevel"
    >
      <div class="urlListItemNum">{{ mindex + 1 }}级</div>
      <draggable
        v-model="group1[mindex]"
        handle=".move"
        animation="150"
        :disabled="disabled"
        @end="moveItem(mindex, 0)"
      >
        <div
          class="urlListItem"
          v-for="(item, index) in filterGroup(group)"
          :key="index"
          @click="setItem(mindex, index, item)"
          :class="{ active: active[mindex] === index }"
        >
          <div class="move" style="float: left; cursor: move" title="拖动排序">
            <i
              style="font-size: 12px"
              class="V7_iconfont V7_iconV7tubiao_yidong"
            ></i>
          </div>
          <div class="url">
            <el-input
              v-model="item.value"
              placeholder="请输入选项"
              :maxlength="maxlength"
              :disabled="disabled"
            ></el-input>
          </div>
          <div v-show="!disabled" class="operate">
            <i
              style="font-size: 14px"
              class="el-icon-remove-outline"
              @click.stop="remove(mindex, index)"
            ></i>
          </div>
        </div>
      </draggable>
      <div v-show="!disabled" @click="add(mindex)" class="add-btn">
        <i class="el-icon-plus" />添加选项
      </div>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 级联选择器
 * 设置数据 setData(data:初始数据数组格式，level：层级)
 * 获取数据 getData 会对空值数据进行过滤
 */
import { deepClone } from '@/utils/common';
import { Component, Vue, Prop } from 'vue-property-decorator';
import draggable from 'vuedraggable'
import { v4 as uuidv4 } from 'uuid'
@Component({
  name: 'Cascader',
  components: { draggable }
})
export default class Cascader extends Vue {
  [x: string]: any
  @Prop({ default: false }) private disabled!: boolean
  @Prop({ default: 50 }) private maxlength!: number
  // 五个数组保存不同层级的数据
  private group1: any = [
    [],
    [],
    [],
    [],
    []
  ]

  // 当前各个层级选中的index
  private active = [
    -1,
    -1,
    -1,
    -1,
    -1
  ]

  private currentMinIndex: number = -1
  // 最大层级 默认两级
  private maxLevel = 2

  private filterGroup (val) {
    if (val) {
      return val.filter(item => !item.isDelete)
    }
  }

  // 初始化数据
  private setData (data, level, onlyShow?) {
    this.$set(this.group1, 0, data)
    this.maxLevel = level
    this.disabled = onlyShow
  }

  // 设置层级
  private setLevel (level) {
    if (level >= this.maxLevel) {
      this.maxLevel = level
    } else {
      this.maxLevel = level
      this.filterData(this.group1[0], 1)
      // const newData = JSON.parse(JSON.stringify(this.group1[0]))
      // newData.map(v => {
      //   this.filterData(v, 1)
      // })
      // this.setData(newData, level)
      this.$set(this.active, level - 1, -1)
      for (let i = level; i < 5; i++) {
        this.$set(this.active, i, -1)
        this.$set(this.group1, i, [])
      }
    }
  }

  // 层级改变时需要清除之前得数据
  private filterData (data, level) {
    data.forEach(item => {
      if (level > this.maxLevel) {
        item.isDelete = 1
      }
      if (item && item.children) {
        this.filterData(item.children, level + 1)
      }
    })
    // if (level === this.maxLevel) {
    //   data.children = null
    // } else if (data.children) {
    //   data.children.map(v => {
    //     this.filterData(v, level + 1)
    //   })
    // }
  }

  private setIsDelete (val) {
    val.forEach(item => {
      item.isDelete = 1
      if (item.children) {
        this.setIsDelete(item.children)
      }
    })
  }

  // 删除数据，如果删除的是当前选中的，需要处理下一层级数据
  private remove (mindex, index) {
    const currentItem = this.group1[mindex].filter(item => !item.isDelete)[index]
    currentItem.isDelete = 1
    if (currentItem.children) {
      this.setIsDelete(currentItem.children)
    }
    // this.group1[mindex].splice(index, 1)
    // if (index === this.active[mindex]) {
    //   this.$set(this.active, mindex, -1)
    //   for (let i = mindex + 1; i < this.maxLevel; i++) {
    //     this.$set(this.active, i, -1)
    //     this.$set(this.group1, i, [])
    //   }
    // }
  }

  // 添加数据
  private add (mindex) {
    const sliceArr = this.active.slice(0, mindex)
    if (sliceArr.some(item => item === -1)) {
      this.$message.warning('请依次选中要插入的父级')
    } else {
      this.group1[mindex].push({
        value: '',
        key: uuidv4().replace(/-/g, ''),
        isDelete: 0
      })
    }
  }

  // 设置当前选中数据
  private setItem (mindex, index, currentItem) {
    // if (!this.disabled) {
    this.currentMinIndex = mindex
    if (mindex < this.maxLevel - 1) {
      this.$set(this.active, mindex, index)
      for (let i = mindex + 1; i < this.maxLevel; i++) {
        this.$set(this.active, i, -1)
        this.$set(this.group1, i, [])
      }
      if (!currentItem.children) {
        this.$set(currentItem, 'children', [])
      }
      this.$set(this.group1, mindex + 1, currentItem.children)
    }
    // }
  }

  private moveItem (mindex, index) {
    if (mindex < this.maxLevel - 1) {
      this.$set(this.active, mindex, index)
      for (let i = mindex + 1; i < this.maxLevel; i++) {
        this.$set(this.active, i, -1)
        this.$set(this.group1, i, [])
      }
      if (!this.group1[mindex][index].children) {
        this.$set(this.group1[mindex][index], 'children', [])
      }
      this.$set(this.group1, mindex + 1, this.group1[mindex][index].children)
    }
  }

  // 获取数据
  private getData () {
    return this.removeLoop(deepClone(this.group1[0] ? this.group1[0] : []))
  }

  private removeEmpty (data) {
    const newData: any = []
    data.map(v => {
      if (v.value !== '') {
        newData.push(v)
      }
    })
    return newData
  }

  // 过滤name为空的数据
  private removeLoop (inData) {
    inData.map(v => {
      if (v.children && v.children.length > 0) {
        v.children = this.removeEmpty(v.children)
        this.removeLoop(v.children)
      } else {
        v.children = null
      }
    })
    return {
      children: inData,
      level: this.maxLevel
    }
  }
}
</script>

<style lang="stylus" scoped>
.urlBox
  overflow auto
  white-space nowrap
  display flex
  .urlList
    border 1px solid #E7E9ED
    width 200px
    border-radius 4px
    overflow hidden
    flex 1 0 auto
    flex-basis 200px
    margin 5px
    display inline-block
    .active
      color #008cee
      background #e5f3fd
    .V7_iconfont
      color #B3B9C7
      font-size 12px
    .add-btn
      cursor pointer
      color #008BEE
      margin-left 16px
      font-size 12px
      .el-icon-plus
        margin-right 5px
    .urlListItemNum
      border-bottom 1px solid #E7E9ED
      padding 0 15px
      font-size 12px
      color #303753
      font-family PingFang SC
    .urlListItem
      line-height 32px
      padding 5px 16px 5px 10px
      font-size 12px
      overflow hidden
      .url
        width calc(100% - 50px)
        float left
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
        margin-left 10px
      .operate
        float right
        line-height 32px
        i
          font-size 12px
          color #B3B9C7
          margin-left 13px
          cursor pointer
        i:hover
          color $c-danger
</style>
